package com.chinamobile.websocket.util;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;

import java.text.SimpleDateFormat;
import java.util.List;

/**
 * Json格式处理类
 */
public final class JsonUtil {
    private static final ObjectMapper objectMapper = new ObjectMapper();
    private static final Logger logger = LoggerFactory.getLogger(JsonUtil.class);

    static {
        objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
    }


    /**
     * 将Object对象转换成Json
     */
    public static String convertObject2Json(Object object) {
        try {
            return objectMapper.writeValueAsString(object);
        } catch (Exception e) {
            logger.error("convertObject2Json", e);
            return null;
        }
    }


    /**
     * 将Json转换成Object对象
     */
    public static <T> T convertJson2Object(String json, Class<T> cls) {
        try {
            return objectMapper.readValue(json, cls);
        } catch (Exception e) {
            logger.error("convert json error.", e);
            return null;
        }
    }


    /**
     * 将Json转换成List<Object>对象
     */
    public static <T> List<T> convertJson2ListObject(String json, Class<T> cls) {
        try {
            return objectMapper.readValue(json, objectMapper.getTypeFactory().constructCollectionType(List.class, cls));
        } catch (Exception e) {
            logger.error("convert json error.", e);
            return null;
        }
    }


    /**
     * 将对象转换为byte数组
     */
    public static byte[] convertObject2Bytes(Object object) {
        try {
            return objectMapper.writeValueAsBytes(object);
        } catch (Exception e) {
            logger.error("convert error.", e);
            return null;
        }
    }


    /**
     * 将byte数组转换为对象
     */
    public static <T> T convertBytes2Object(byte[] objectBytes, Class<T> clazz) {
        try {
            return objectMapper.readValue(objectBytes, clazz);
        } catch (Exception e) {
            logger.error("convert error.", e);
            return null;
        }
    }

    /**
     * 将 JsonObject 转换成Object对象
     *
     * @param jsonObject
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T json2Obj(JSONObject jsonObject, Class<T> clazz) {
        try {
            if (CollectionUtils.isEmpty(jsonObject)) {
                return null;
            }
            return objectMapper.readValue(jsonObject.toJSONString(), clazz);
        } catch (Exception e) {
            logger.error(" json error.", e);
            return null;
        }
    }

}
